<template>
  <link rel="stylesheet" href="/jf-knowledge-plugins/cdn/luckysheet/plugins/css/pluginsCss.css" />
  <link rel="stylesheet" href="/jf-knowledge-plugins/cdn/luckysheet/plugins/plugins.css" />
  <link rel="stylesheet" href="/jf-knowledge-plugins/cdn/luckysheet/css/luckysheet.css" />
  <link rel="stylesheet" href="/jf-knowledge-plugins/cdn/luckysheet/assets/iconfont/iconfont.css" />
  <link rel="stylesheet" href="/jf-knowledge-plugins/cdn/luckysheet/assets/customicon/iconfont.css" />
  
  <div class="hello" id="screenContent" :class="[!isShare&&!isMobile_new&&'view-file-pc',isMobile_new && 'mobile-luckysheet',isTemplate&&!isEdit && 'template-view-box']">
    <div
      id="luckysheet"
      :style="`
        padding: ${isEdit ? '0px' : '0px'};
        position: absolute;
        width: ${isEdit?(showPivot?'calc(100% - 260px)':'calc(100% - 0px)'):(showPivot?'calc(100% - 272px)':'calc(100% - 12px)')};
        height: ${(isMobile_new||isTemplate||isWritingPreview)?'calc(100% - 0px)':isEdit||isShare ? 'calc(100% - 0px)' : isWritingPreview?'calc(100% - 68px)': '100%'};
        left: 0px;
        top: ${isMobile_new?'0px':isEdit ? '0px' : (isShare||isTemplate || isWritingPreview)?'0': '0px'};
        bottom: 0px;`
      "
    ></div>
    <div id="print-area" style="
      display: none;
      position: absolute;
      z-index: -1;
      top: 0;
      width: 100%;
      height: 100vh;
      overflow: hidden;">
        <div id="print-html" ref="printPayFeeNew"></div>
    </div>
    <div id="pivot-box" v-show="showPivot"></div>
  </div>
</template>
<script lang="ts">
import scriptjs from 'scriptjs'

function fetchScript(url: string | string[]) {
  return new Promise<void>((resolve) => {
    scriptjs(url, () => {
      resolve()
    })
  })
}
await fetchScript('/jf-knowledge-plugins/cdn/luckysheet/plugins/js/plugin.js')
await fetchScript('/jf-knowledge-plugins/cdn/luckysheet/luckysheet.umd.js')

</script>
<script setup lang="ts">
import {
  ref,
  watch ,
  onMounted,
  nextTick,
  computed,
  getCurrentInstance,
  onUnmounted
} from 'vue' 
import type { ComponentInternalInstance } from 'vue'
import { useRoute } from "vue-router"
import { preview, getShareInfo, saveContent,uploadTemplateCover } from "@/api/common";
import { getTemplateInfo,saveTemplateContent,saveTemplate } from '@/api/template'
import { saveVersion } from '@/api/version'
// import version from '@/components/version/index.vue'
import luckySheetStore from '@/store/luckySheet';
import useSocketStore from '@/store/socket';
import useUserInfoStore from '@/store/userInfo';
import { socketStatus } from '@/const/socketStatus'
import { exportExcel } from '@/utils/export'
import { useHookI18n } from '@/hooks/i18n'

import { multipleRangeShow, muitipleRangeHide, multipleRangeRefresh } from './lucksheet'
import useCommonStore from '@/store/common';

const route = useRoute()
const { locale,$t } = useHookI18n()
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
const userStore = useUserInfoStore()
const lsStore = luckySheetStore()
const socketStore = useSocketStore()
const commonStore = useCommonStore()



const emit = defineEmits(["contetnChange","renderFinish",'changeLatelySave'])
const props = defineProps({
  isPrivew:{
      type:Boolean,
      default:false
  },
  readonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  isEdit: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  id: {
    type: String,
    default: () => {
      return '';
    },
  },
  formShare: {
    type: Boolean
  },
  isTemplate:{
    type:Boolean,
    default:false
  },
  isWritingPreview:{
    type: Boolean,
    default: () => {
      return false;
    },
  },
  docInfo: {
    type: Object,
    default: () => {
      return {};
    }
  }
})
const isShare = ref(false)
interface userInfo{
  id: string,
  name: string,
  r: string|number,
  c: string|number,
  op: any
}
const initUserInfoList = ref<userInfo[]>([])
const content = ref([])

// 选中的区域坐标 r  c
const selectPos = ref([])
// 是否来自其他人编辑
const fromOther = ref(false)
// 默认初始化数据 来自远程
const allData = ref<any>(null)
// 起始协同人员列表

// 坐标点所有协同人员列表

// 是否是通过ws添加
const isWsAddSheet = ref(false)
// 是否是通过ws修改名称
const isWsChangeName = ref(0)
// 是否是通过ws同步复制sheet

// 是否是通过ws删除Sheet
const isWsDelSheet = ref(0)
// 选中光标的协同人员
interface selectUser{
  userId: string,
  userName:string,
  r:string|number,
  c:string|number,
  op:any,
  sheetIndex:string|number
}
const selectUserObj = ref<selectUser[]>([])
// 当前的选区对象

const printPayFeeNew = ref()
const editorStatus = ref(true)
const getWsMsg = computed<any>(()=>{
  return socketStore.socketMsg
})
const showPivot = ref(false)
const isMobile_new = computed(()=>{
  let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
  return flag;
})
watch(getWsMsg,(newV)=>{
  if(!props.readonly){
    let command = socketStatus[newV.command as keyof typeof socketStatus] || newV.command
    switch (command+'') {
      case '10':
        if(newV.data){
          muitipleRangeHide(newV.data.user.userId)
        }
        break;
      case '20':
        if(newV.data?.business){
          let content = newV.data.business.content
          if(content.type == 'allData') {
            allData.value = content.data
            console.log(allData.value)
          }
        }
        break;
      case '26':
        if(newV.data && userStore.userInfo.id != newV.data.from) {
          if(window.luckysheet && newV.data.content) {
            let content = newV.data.content
            fromOther.value = true
            let currentSheet
            switch(content.type){
              case "addSheet":
                if(checkHaveSheet(content.data.sheetconfig.index)){
                  return
                }
                isWsAddSheet.value = true
                currentSheet = luckysheet.getSheet()

                window.luckysheet.setSheetAdd(Object.assign(content.data.sheetconfig,{
                  success:function(){
                    window.luckysheet.setSheetActive(currentSheet.order)
                    activeSheetShowUser(currentSheet.index)
                    setTimeout(()=>{
                      isWsAddSheet.value = false
                    },1000 * 0.1)
                  }
                }))
                break
              case "copySheet":
                if(!checkHaveSheet(content.data.order)){
                  return
                }
                isWsAddSheet.value = true
                currentSheet = luckysheet.getSheet()
                window.luckysheet.setSheetAdd({
                  sheetObject:content.data,
                  order:content.data.order,
                  success:function(){
                    let newOrder = luckysheet.getSheet({index:currentSheet.index})
                    window.luckysheet.setSheetActive(newOrder.order)
                    activeSheetShowUser(newOrder.index)
                    setTimeout(()=>{
                      isWsAddSheet.value = false
                    },1000 * 0.1)
                  }
                })
                break
              case "deleteSheet":
                if(!checkHaveSheet(content.data.order)){
                  return
                }
                isWsDelSheet.value +=1
                currentSheet = luckysheet.getSheet()
                window.luckysheet.setSheetDelete({
                  order:content.data.order,
                  success:()=>{
                    if(content.data.order==currentSheet.order){
                      proxy.$confirm(`${$t('message.confirm.luckySheetDeleteStart')}${content.data.name}${$t('message.confirm.luckySheetDeleteEnd')}`, $t('message.prompt'), {
                        confirmButtonText: $t('message.buttons.submit'),
                        showCancelButton:false,
                        type: 'warning'
                      }).then(() => {
                      }).catch(() => {
                      });
                    }
                    setTimeout(()=>{
                      isWsDelSheet.value -= 1
                      if(isWsDelSheet.value<0){
                        isWsDelSheet.value = 0
                      }
                    },1000 * 0.1)
                  }
                });
                break
              case "setCellValue":
                if(!checkHaveSheet(content.activeSheetOrder)){
                  return
                }
                window.luckysheet.setCellValue(content.data.row, content.data.column, content.data.value, {
                  order:content.activeSheetOrder
                })
                break;
              case "rangeSelect":
                if(newV.data.content.data) {
                  let currentSheet = luckysheet.getSheet()
                  let user = newV.data.content.user
                  if(user.id != userStore.userInfo.id && currentSheet.index == newV.data.content.data.i) {
                    let value = newV.data.content.data.v
                    let r = value.range[value.range.length - 1].row[0];
                    let c = value.range[value.range.length - 1].column[0];
                    multipleRangeShow(user.id, user.name, r, c, value.op);
                    selectUserObj.value.push({
                      userId:user.id,
                      userName:user.name,
                      r:r,
                      c:c,
                      op:value.op,
                      sheetIndex:newV.data.content.data.i
                    })
                  }else{
                    muitipleRangeHide(user.id)
                  }
                }
                break;
              case "changeVersion":
                proxy.$confirm($t('message.confirm.versionBack'), $t('message.message.contentChanged'), {
                  confirmButtonText: $t('message.buttons.submit'),
                  cancelButtonText: $t('message.buttons.cancal'),
                  type: 'warning'
                }).then(() => {
                  saveVersionFun(false,function(){
                    content.value = JSON.parse(content)
                    window.luckysheet.destroy();
                    init()
                  })
                }).catch(() => {
                  content.value = JSON.parse(content)
                  window.luckysheet.destroy();
                  init()
                });
                break
              case "sheetName":
                if(!checkHaveSheet(content.data.order)){
                  return
                }
                isWsChangeName.value +=1
                window.luckysheet.setSheetName(content.data.txt,{
                  order:content.data.order,
                  success:()=>{
                    setTimeout(()=>{
                      isWsChangeName.value -= 1
                      if(isWsChangeName.value<0){
                        isWsChangeName.value = 0
                      }
                    },1000 * 0.1)
                  }
                });
                break
              case 'resize':
              case 'borderChange':
                luckysheet.setConfig(content.data.curconfig,{
                  order:content.data.order,
                  success(){
                    if(content.data.order==luckysheet.getSheet().order){
                      lsStore.flowdata = luckysheet.getSheet().data
                      lsStore.visibledatarow = luckysheet.getSheet().visibledatarow
                      lsStore.visibledatacolumn = luckysheet.getSheet().visibledatacolumn
                      refreshRange(content.data.order)
                    }                    
                  }
                })
                break
              default: ;break;
            }
          }
        }
        break;
      case "28":
        if(newV.data){
          let data = typeof newV.data==='string'?JSON.parse(newV.data):newV.data
          if(data.extras && data.extras.content) {
            let content = data.extras.content
            if(content.type == 'rangeSelect') {
              let currentSheet = luckysheet.getSheet()
              let user = content.user
              if(user.id != userStore.userInfo.id && currentSheet.index == content.data.i) {
                let value = content.data.v
                let r = value.range[value.range.length - 1].row[0];
                let c = value.range[value.range.length - 1].column[0];
                multipleRangeShow(user.id, user.name, r, c, value.op);
                let isChange = false
                selectUserObj.value.forEach(item=>{
                  if(item.userId == user.id){
                    isChange = true
                    item.r = r
                    item.c = c
                    item.op = value.op
                    item.sheetIndex = content.data.i
                  }
                })
                if(!isChange){
                  selectUserObj.value.push({
                    userId:user.id,
                    userName:user.name,
                    r:r,
                    c:c,
                    op:value.op,
                    sheetIndex:content.data.i
                  })
                }
              }else{
                muitipleRangeHide(user.id)
              }
            }
          }
        }
        break;
      case '32':
        initUserInfoList.value = []
        for(let u of newV.data.users) {
          if(u.userId != userStore.userInfo.id && u.extras) {
            let tvalue = u.extras.content.data.v
            let r = tvalue.range[tvalue.range.length - 1].row[0];
            let c = tvalue.range[tvalue.range.length - 1].column[0];
            initUserInfoList.value.push({
              id: u.extras.content.user.id,
              name: u.extras.content.user.name,
              r: r,
              c: c,
              op: tvalue.op
            })
            let isChange = false
            selectUserObj.value.forEach(item=>{
              if(item.userId == u.extras.content.user.id){
                isChange = true
                item.r = r
                item.c = c
                item.op = tvalue.op
                item.sheetIndex = u.extras.content.data.i
              }
            })
            if(!isChange){
              selectUserObj.value.push({
                userId: u.extras.content.user.id,
                userName:u.extras.content.user.name,
                r:r,
                c:c,
                op:tvalue.op,
                sheetIndex:u.extras.content.data.i
              })
            }
          }
        }
        break;
      default:
        break;
    }
  }
})
onMounted(()=>{
  if (props.isEdit && userStore.access_token && !props.isTemplate) {
      socketStore.INIT(props.id)
    }
  isShare.value = window.location.href.indexOf('detail') > -1
  setTimeout( () => {
    getData()
  }, 1000)
  setTimeout( () => {
    for(let user of initUserInfoList.value) {
      multipleRangeShow(user.id, user.name, user.r,user.c, user.op);
    }
  }, 3000)
})
onUnmounted(()=>{
  window.luckysheet.destroy();  
})
// 判定是否有当前的这个sheet
function checkHaveSheet(val){
  let sheetArry = luckysheet.getAllSheets()
  let isHave = false
  sheetArry.forEach(item=>{
    if(item.order==val || item.index==val){
      isHave = true
    }
  })
  return isHave
}

watch(()=>props.id,(newV,oldV)=>{
  if(newV!=oldV){
    getData()
  }
})

function getData(){
  let fun = preview
  if(props.formShare) {
    fun = getShareInfo
  }
  if(route.query.type == 'template' || props.isTemplate){
    fun = getTemplateInfo
  }
  fun(props.id).then((res) => {
    if (res.data.code == 0 && res.data.data) {
      if (res.data.data.content && res.data.data.content.startsWith("{")) {
        let resData = JSON.parse(JSON.parse(res.data.data.content).content);
        content.value = [...resData];
      } else {
        content.value = [];
      }
      init()
    }
  });
}
function handleSend(data) {
    socketStore.SEND_MESSAGE(data)
}
function refreshRange(order){
  nextTick(()=>{
    for(let range of selectUserObj.value){
      multipleRangeRefresh(range.userId,range.userName,range.r,range.c,order)
    }
  })
}
function init(){
  var options={
    container: "luckysheet",
    pivotDom:'#pivot-box',
    // prvotDomWidth:400,
    noCalcPrvotWidth:true,
    // noUpdateFa:true,
    lang:locale.value.indexOf('zh')!=-1?'zh':'en',
    showGridLines:true,
    allowUpdate: !props.readonly && !props.isPrivew,
    allowEdit:!props.readonly && !props.isPrivew,
    showinfobar: false, // 是否显示顶部信息栏
    showsheetbar: true, // 是否显示底部sheet页按钮
    showstatisticBar: false, // 是否显示底部计数栏
    enableAddBackTop: !props.readonly,// sheet页下方的回到顶部按钮
    enableAddRow:!props.readonly && !props.isPrivew,// sheet页下方的添加行按钮
    userInfo: false, // 右上角的用户信息展示样式
    plugins: ['chart'],
    sheetFormulaBar: !props.readonly,
    showstatisticBarConfig: {
      count:true,
      view:true,
      zoom:true,
    },
    showtoolbarConfig:{
      undoRedo: !props.readonly, //撤销重做，注意撤消重做是两个按钮，由这一个配置决定显示还是隐藏
      paintFormat: !props.readonly, //格式刷
      currencyFormat: !props.readonly, //货币格式
      percentageFormat: !props.readonly, //百分比格式
      numberDecrease: !props.readonly, // '减少小数位数'
      numberIncrease: !props.readonly, // '增加小数位数
      moreFormats: !props.readonly, // '更多格式'
      font: !props.readonly, // '字体'
      fontSize: !props.readonly, // '字号大小'
      bold: !props.readonly, // '粗体 (Ctrl+B)'
      italic: !props.readonly, // '斜体 (Ctrl+I)'
      strikethrough: !props.readonly, // '删除线 (Alt+Shift+5)'
      underline: !props.readonly, // '下划线 (Alt+Shift+6)'
      textColor: !props.readonly, // '文本颜色'
      fillColor: !props.readonly, // '单元格颜色'
      border: !props.readonly, // '边框'
      mergeCell: !props.readonly, // '合并单元格'
      horizontalAlignMode: !props.readonly, // '水平对齐方式'
      verticalAlignMode: !props.readonly, // '垂直对齐方式'
      textWrapMode: !props.readonly, // '换行方式'
      textRotateMode: !props.readonly, // '文本旋转方式'
      image:!props.readonly, // '插入图片'
      link:!props.readonly, // '插入链接'
      chart: false, // '图表'（图标隐藏，但是如果配置了chart插件，右击仍然可以新建图表）
      postil:  !props.readonly, //'批注'
      pivotTable: !props.readonly,  //'数据透视表'
      function: !props.readonly, // '公式'
      frozenMode: !props.readonly, // '冻结方式'
      sortAndFilter: !props.readonly, // '排序和筛选'
      conditionalFormat: !props.readonly, // '条件格式'
      dataVerification: !props.readonly, // '数据验证'
      splitColumn: !props.readonly, // '分列'
      screenshot: !props.readonly, // '截图'
      findAndReplace: !props.readonly, // '查找替换'
      protection:!props.readonly, // '工作表保护'
      gridLines:false, // 网格线
      print:!props.readonly, // '打印'
      export:false ,// 导出
      pager:false, //分页
      refresh:false
    },
    showsheetbarConfig: {
      add: !props.readonly, //新增sheet
      menu: false, //sheet管理菜单
      sheet: true, //sheet页显示
    },
    sheetRightClickConfig:{
      delete: !props.readonly, // 删除
      copy: false, // 复制
      rename: !props.readonly, //重命名
      color: false, //更改颜色
      hide: false, //隐藏，取消隐藏
      move: false, //向左移，向右移
    },
    cellRightClickConfig:{
      copy: true, // copy
      copyAs: true, // copy as
      paste: true, // paste
      insertRow: true, // insert row
      insertColumn: true, // insert column
      deleteRow: true, // delete the selected row
      deleteColumn: true, // delete the selected column
      deleteCell: true, // delete cell
      hideRow: true, // hide the selected row and display the selected row
      hideColumn: true, // hide the selected column and display the selected column
      rowHeight: true, // row height
      columnWidth: true, // column width
      clear: true, // clear content
      matrix: true, // matrix operation selection
      sort: true, // sort selection
      filter: true, // filter selection
      chart: false, // chart generation
      image: true, // insert picture
      link: true, // insert link
      data: true, // data verification
      cellFormat: true // Set cell format
    },
    hook: {
      // 框选或者设置选区后触发
      rangeSelect (sheet, range) {
        if(!props.readonly) {
            lsStore.flowdata = sheet.data
            lsStore.visibledatarow = sheet.visibledatarow
            lsStore.visibledatacolumn = sheet.visibledatacolumn
          let d = {};
          d.t = "mv";
          d.i = sheet.index;
          d.v = {op:"enterEdit", range: range};
          // console.log('这里是触发选区选中',d)
          handleSend({
            cmd: 27,
            userId: userStore.userInfo.id,
            groupId: props.id + '-knowledge-ui',
            extras: {
              content: {
                type: 'rangeSelect',
                data: d,
                user: {
                  id: userStore.userInfo.id,
                  name: userStore.userInfo.realName,
                  avatar: userStore.userInfo.headImg
                }
              }
            }
          })
        }
      },
      // 鼠标按钮释放事件，可通过cell判断鼠标停留在哪个单元格
      sheetMouseup(){
        emit("contetnChange", luckysheet.getAllSheets());
      },
      // 进入单元格编辑模式之前触发。在选中了某个单元格且在非编辑状态下
      cellEditBefore (range) {
        // selectPos.value = []
        let currentSheet = luckysheet.getSheet()
        for(let i in range) {
          if(range[i].column&& range[i].row){
            selectPos.value.push({
              c: range[i].column[0],
              r: range[i].row[0],
              sheetOrder:currentSheet.order,
              isSend: false
            })
          }
        }
      },
      // 单元格渲染结束后触发，return false 则不渲染该单元格
      cellRenderAfter (cell, position, sheet, ctx) {
        /**
         * cell 单元格对象
         * position :
         * {Number} [r]:单元格所在行号
         * {Number} [c]:单元格所在列号
         * {Number} [start_r]:单元格左上角的水平坐标
         * {Number} [start_c]:单元格左上角的垂直坐标
         * {Number} [end_r]:单元格右下角的水平坐标
         * {Number} [end_c]:单元格右下角的垂直坐标
         * sheet  当前sheet对象
         * ctx  当前画布的context
         */
        if(cell) {
          for(let i = 0 ;i<selectPos.value.length;i++){
          // for(let i in selectPos.value) {
            // if(selectPos.value[i].c == position.c && selectPos.value[i].r == position.r && !selectPos.value[i].isSend) {
            //   selectPos.value[i].isSend = true
            if(selectPos.value[i].c == position.c && selectPos.value[i].r == position.r) {
              let obj =  { type: 'setCellValue', activeSheetOrder: selectPos.value[i].sheetOrder, data: { row: position.r, column: position.c, value: cell } }
              let businessId = props.id + '-knowledge-ui'
              let userId = userStore.userInfo.id
              let joinData = {
                cmd: 25,
                from: userId,
                businessId: businessId,
                expire: 60 * 60,
                content: obj
              }
              if(fromOther.value) {
                fromOther.value = false
              }else{
                handleSend(joinData)
                if(window.luckysheet) {
                  let all = {
                    cmd: 25,
                    from: userId,
                    businessId: businessId,
                    expire: 60 * 60,
                    content: {type : 'allData', data: window.luckysheet.getAllSheets()}
                  }
                  handleSend(all)
                }
              }
              selectPos.value.splice(i,1)
              i--
            }
          }
        }
      },
      updated:function(operate){
        console.log(operate)
        let businessId = props.id + '-knowledge-ui'
        let userId = userStore.userInfo.id
        let sheetNameObj = window.luckysheet.getSheet({index:operate.sheetIndex})
        if((operate.type=="addSheet" || operate.type=='copySheet') && !isWsAddSheet.value){
          let obj =  { type: operate.type, data: operate }
          if(operate.type=='copySheet'){
            obj = {type: operate.type, data: sheetNameObj}
          }
          let joinData = {
            cmd: 25,
            from: userId,
            businessId: businessId,
            expire: 60 * 60,
            content: obj
          }
          handleSend(joinData)
          setTimeout(()=>{
            isWsAddSheet.value = false
          },1000 * 0.1)
        }
        if(operate.type == 'datachange' && !fromOther.value){
          let currentSheet =window.luckysheet.getSheet({index:operate.sheetIndex})
          let colStart = operate.range[0].column[0],colEnd = operate.range[0].column[1]+1,
          rowStart = operate.range[0].row[0], rowEnd = operate.range[0].row[1]+1
          for(;colStart<colEnd;colStart++){
            for(;rowStart<rowEnd;rowStart++){
              let cell = operate.curdata[rowStart][colStart]
              let obj =  { type: 'setCellValue', activeSheetOrder: currentSheet.order, data: { row: rowStart, column: colStart, value: cell } }
              let joinData = {
                cmd: 25,
                from: userId,
                businessId: businessId,
                expire: 60 * 60,
                content: obj
              }
              handleSend(joinData)
            }
          }
          let all = {
            cmd: 25,
            from: userId,
            businessId: businessId,
            expire: 60 * 60,
            content: {type : 'allData', data: window.luckysheet.getAllSheets()}
          }
          handleSend(all)
        }
        if(operate.type == 'datachange' && fromOther.value){
          fromOther.value = false
        }
        if(operate.type=='deleteSheet' && isWsDelSheet.value==0){
          let obj =  { type: 'deleteSheet', data: operate }
          let joinData = {
            cmd: 25,
            from: userId,
            businessId: businessId,
            expire: 60 * 60,
            content: obj
          }
          handleSend(joinData)
          setTimeout(()=>{
            isWsDelSheet.value -= 1
            if(isWsDelSheet.value<0){
              isWsDelSheet.value = 0
            }
          },1000*0.1)
        }
        if(operate.type=='sheetName' && isWsChangeName.value==0){
          let obj =  { type: operate.type, data: Object.assign({},operate,{
              order:sheetNameObj.order
            })
          }
          let joinData = {
            cmd: 25,
            from: userId,
            businessId: businessId,
            expire: 60 * 60,
            content: obj
          }
          handleSend(joinData)
          setTimeout(()=>{
            isWsChangeName.value -= 1
            if(isWsChangeName.value<0){
              isWsChangeName.value = 0
            }
          },1000*0.1)
        }
        if(['resize','borderChange'].indexOf(operate.type) !=-1){
          handleSend({
            cmd:25,
            from:userId,
            businessId:businessId,
            expire: 60 * 60,
            content: {
              type:operate.type,
              data:{
                config:operate.config,
                curconfig:operate.curconfig,
                order:sheetNameObj.order
              }
            }
          })
          lsStore.flowdata = luckysheet.getSheet().data
          lsStore.visibledatarow = luckysheet.getSheet().visibledatarow
          lsStore.visibledatacolumn = luckysheet.getSheet().visibledatacolumn
          refreshRange(sheetNameObj.order)
        }
      },
      printData:function(type,index){
        switch (type) {
          case 'print':
            let RowColumn = getExcelRowColumn() // 获取有值的行和列
            RowColumn.column[0] = 0 //因需要打印左边的边框，需重新设置
            luckysheet.setRangeShow(RowColumn) // 进行选区操作
              // 生成base64图片
          case 'areas':
          default:
            let src = luckysheet.getScreenshot();
            let $img = `<img src=${src} style="width: 100%;position: absolute;left:0px" />`;
            document.querySelector("#print-area").style.display = "block";
            nextTick(() => {
              document.querySelector("#print-html").innerHTML = $img;
              proxy.$print(printPayFeeNew.value,{
                callBack:function(){
                  document.querySelector("#print-area").style.display = "none";
                }
              }) // Print.js插件
            });
            break;
        }
      },
      // 激活某个sheet的时候渲染
      sheetActivate:function(index, isPivotInitial, isNewSheet){
        let currentSheet = luckysheet.getSheet()
        selectPos.value = [{
          c: 0,
          r: 0,
          sheetOrder:currentSheet.order,
          isSend: false
        }]
        activeSheetShowUser(index)
        // window.luckysheet.setRangeShow("A1")
      },
      // 数据透视图显影的变化
      openPivot(value){
        showPivot.value = value
        nextTick(()=>{
          handleResize()
        })
      },
    },
  }
  try {
    if(content.value==''){
      luckysheet.create({
        ...options,
        data: allData.value ? allData.value :[
          {
            "name": "Sheet1",
            "color": "",
            "index": 0,
            "status": 0,
            "order": '0',
            "celldata": [],
            "config": {}
          },
        ],
      });
    }else{
      luckysheet.create({
        ...options,
        data: allData.value ? allData.value : content.value,
      });
    }
    emit("renderFinish")
  } catch (error) {
    emit("renderFinish")    
  }
}
function activeSheetShowUser(index){
  selectUserObj.value.forEach(item => {
    if(item.userId != userStore.userInfo.id && index== item.sheetIndex){
      multipleRangeShow(item.userId, item.userName, item.r, item.c, item.op);
    }
  });
}
function getExcelRowColumn() {
  const sheetData = luckysheet.getSheetData();
  let objRowColumn = {
    row: [null, null], //行
    column: [null, null], //列
  };
  sheetData.forEach((item, index) => {
    //行数
    item.forEach((it, itemIndex) => {
      if (objRowColumn.row[0] == null) objRowColumn.row[0] = index; // row第一位
      if (it !== null) {
        objRowColumn.row[1] = index; //row第二位
        if (objRowColumn.column[0] == null) objRowColumn.column[0] = itemIndex; //column第一位
        if(itemIndex>objRowColumn.column[1] || objRowColumn.column[1] == null){
          objRowColumn.column[1] = itemIndex; //column第二位
        }
      }
    });
  });
  return objRowColumn;
}
//快捷键Ctrl+S保存截屏
function createImg(item) {
  proxy.$eventBus.$emit('changeSaveLoading',true)
  html2canvas(document.getElementById('screenContent'),{
      useCORS: true,
      backgroundColor: null
    }
  ).then((canvas) => {
    const dataUrl = canvas.toDataURL('images/jpg')
    let formData = new FormData();
    formData.append('file', dataURLtoFile(dataUrl, item.name))
    formData.append('module', `/jvs-knowledge-ui/${props.docInfo.id}/fileCover`)
    uploadTemplateCover(formData).then((res) => {
      item.coverUrl = res.data.data.fileLink
      item.coverFilePath = res.data.data.fileName
      item.coverBucketName = res.data.data.bucketName
      item.coverFileSize = res.data.data
      saveTemp(item)
    }).catch(f=>{
        proxy.$eventBus.$emit('changeSaveLoading',false)
    })
  })
}
function dataURLtoFile(dataurl, filename) {
  // 获取到base64编码
  const arr = dataurl.split(',')
  // 将base64编码转为字符串
  const bstr = window.atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n) // 创建初始化为0的，包含length个元素的无符号整型数组
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, {
    type: 'image/png'
  })
}
//修改模板的封面
function saveTemp(item){
  saveTemplate(Object.assign({},item,{
    typeId:item.typeId,
    templateType:'edit',
    ...item
  })).then(res=>{
    if(res.data.code == 0 ){
      proxy.$notify({
        title: $t('message.message.saveTemplateSuccess'),
        type: "success",
        position: "bottom-right",
      });
    }
  }).finally(f=>{
      proxy.$eventBus.$emit('changeSaveLoading',false)
  })
}
function handleSave() {
  let fun = saveContent
  if(props.isTemplate){
    let item = props.docInfo
    createImg(item)
    fun = saveTemplateContent
  }
  let viewString = JSON.stringify(luckysheet.getAllSheets())
  fun(props.id, { content: viewString }).then( res => {
    if (res.data.code == 0) {
      proxy.$onePrompt.$oneNotify({
        title:$t('message.message.saveSuccess'),
        type: "success",
        position: "bottom-right",
      });
      emit("changeLatelySave",new Date())
    }
  }); 
}
function saveVersionFun(type:Boolean=true,backFunction:Function){
  let viewString = JSON.stringify(window.luckysheet.getAllSheets())
  saveVersion({
    dcId:props.id,
    content:viewString
  }).then(res=>{
    if(res.data.code == 0){
      if(type){
        proxy.$notify({
          title: $t('message.message.generatedVersionSuccess'),
          type: "success",
          position: "bottom-right",
        });
      }
      if(backFunction){
        backFunction()
      }
    }
  })
}
function handleResize(){
  luckysheet.resize()
}
function changeEditStatus(){
  if(editorStatus.value){
    luckysheet.closeWorkBookEditMode()
  }else{
    luckysheet.openWorkBookEditMode()
  }
  editorStatus.value = !editorStatus.value
}
function downFile(item){
  let storeDownItem = {
    id:item.id,
    name:item.name,
    isFinish:false,
    downTime:new Date().getTime()
  }
  let soteDownList = commonStore.downFileList
  soteDownList.push(storeDownItem)
  commonStore.setDownLoadFileList(soteDownList)
  exportExcel(content.value,item.name,function(){
    soteDownList.forEach((item)=>{
      if(item.downTime==storeDownItem.downTime){
        item.isFinish = true
      }
    })
    commonStore.setDownLoadFileList(soteDownList)
    proxy.$notify({
        title: $t('message.buttons.download'),
        messag: $t('message.message.downloadSuccess'),
        type:'success',
        positon:'bottom-right'
    })
  })
}
function changeResize(){
  handleResize()
}
function changeVersionContent(content,type){
  if(type=='handleVersion'){
    content.value = JSON.parse(content)
    // 告知其他用户内容已被更改
    let businessId = props.id + '-knowledge-ui'
    let userId = userStore.userInfo.id
    handleSend({
      cmd: 25,
      from: userId,
      businessId: businessId,
      expire: 60 * 60,
      content: { type: 'changeVersion', data: content }
    })
    window.luckysheet.destroy();
    init()
  }
}
function closeShortKey(){}

defineExpose({
  closeShortKey,
  changeEditStatus,
  handleSave,
  handleResize,
  changeResize,
  changeVersionContent,
  saveVersionFun
})
</script>
<style lang="scss" scoped>
.pivot-box{
  width: 260px;
  height: 100%;
  position: absolute;
  right: 0px;
  top: 0px;
}
.hello{
  min-height: 650px;
  position: relative;
}
.view-file-pc{
  height: 100%;
  width: 100%;
  position: absolute;
}
.mobile-luckysheet{
    height: 100%;
}
.template-view-box{
  height: calc(100vh - 252px);
}
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
::v-deep(.luckysheet-scrollbar-ltr){
  z-index:198 !important;
}
</style>